<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select default-value="全部" @change="(e) => updateParam(e, 'status')">
                  <a-select-option value="-1"> 全部 </a-select-option>
                  <a-select-option value="1"> 上架 </a-select-option>
                  <a-select-option value="0"> 下架 </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="商品名称">
                <a-input v-model="queryParam.name" placeholder="请填写搜索商品名称" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button @click="searchGoods" type="primary"> 查询 </a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <span></span>
        <a-button type="primary" style="margin-bottom: 0px" @click="onAdd()" icon="plus">新建</a-button>
      </div>
      <!-- 新列表 -->
      <a-spin :spinning="spinning">
        <GoodsListTable
          ref="listTable"
          :list_th="list_th"
          :pagaData="pagaData"
          @statusChange="statusSwitchChange"
          @triggerAction="listActions"
        >
        </GoodsListTable>
      </a-spin>
      <div style="float: right">
        <Pagination
          v-model="queryParam.pageNo"
          :page-size.sync="pageSize"
          @change="paginationChange"
          :total="totalCount"
          show-less-items
        />
      </div>
      <!-- 新列表 -->

      <a-modal
        title="编辑商品"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        v-model="visible"
        @ok="handleOk"
        @cancel="handleClose"
      >
        <template v-if="is_edit == false">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="选择商品" prop="good">
            <a-button @click="showGoods = true">选择商品</a-button>
            <div class="choosedGood" v-if="choosedGood">
              <span>{{ choosedGood.name }}</span>
              <a-icon type="close-circle" style="cursor: pointer" @click="choosedGood = null" />
            </div>
          </a-form-item>
          <search-goods v-model="showGoods" @onOk="(e) => chooseGood(e)"></search-goods>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规格选择">
            <a-select style="width: 400px" placeholder="规格选择" :default-value="index" @change="handleChange($event)">
              <a-select-option :value="index" v-for="(item, index) of attr" :key="index">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-item>
        </template>
        <template v-else>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规格">
            <a-input disabled placeholder="规格" v-model="commitParams.attr_str" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="原商品名称">
            <a-input disabled placeholder="原商品名称" v-model="commitParams.origin_name" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品名称">
            <a-input placeholder="商品名称" v-model="commitParams.name" />
          </a-form-item>
        </template>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="分类选择">
          <a-select
            style="width: 400px"
            placeholder="分类选择"
            :default-value="cat_id"
            @change="handleCatChange($event)"
          >
            <a-select-option :value="res.id" v-for="(res, index) of cat" :key="index">{{ res.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="图文详情">
          <WangEditor :value="commitParams.detail" @change="onDescChange"></WangEditor>
          <a-textarea :hidden="true" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="所需积分">
          <a-input placeholder="兑换所需要积分" type="number" v-model="commitParams.integral" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="每人限制兑换数量">
          <a-input placeholder="限制兑换数量" type="number" v-model="commitParams.user_num" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品数量">
          <a-input placeholder="商品数量" type="number" v-model="commitParams.goods_count" />
          <span v-if="tip_visiable" style="color: red">当前商品规格库存为：{{ goods_num }}, 请填写小于该值的数</span>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="虚拟销量">
          <a-input placeholder="虚拟销量" type="number" v-model="commitParams.sales" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序">
          <a-input placeholder="排序" type="number" v-model="commitParams.sort" />
        </a-form-item>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { saveGoods, getGoods, goodsList, getAttr, updateStatus, deleteGoods, getCat } from '@/api/plugin/integral'
import { STable, SearchGoods, WangEditor } from '@/components'
import { Pagination } from 'ant-design-vue'

import GoodsListTable from './components/GoodsListTable'

const columns = [
  {
    title: '商品信息',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' },
    width: 100,
  },
  {
    title: '规格',
    dataIndex: 'attr_str',
    width: 150,
  },
  {
    title: '分类',
    dataIndex: 'cat_name',
    width: 20,
  },
  {
    title: '已出售量',
    dataIndex: 'sales',
    width: 20,
  },
  {
    title: '所需积分',
    dataIndex: 'integral',
    width: 20,
  },
  {
    title: '限制兑换数量',
    dataIndex: 'user_num',
    width: 20,
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' },
    width: 20,
  },
  {
    title: '排序',
    dataIndex: 'sort',
    width: 20,
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 20,
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'IntegralGoods',
  components: {
    WangEditor,
    STable,
    SearchGoods,
    GoodsListTable,
    Pagination,
  },
  data() {
    return {
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 5,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 16,
        },
      },
      detail: null,
      cat_id: null,
      cat: [],
      goods_num: 0,
      commitParams: {},
      choosedGood: null,
      columns: columns,
      selectedRowKeys: [],
      goods_id: 0,
      is_edit: false,
      attr: [],
      selectedAttr: null,
      visible: false,
      autoFocusData: { type: '', index: 0 }, // 获取焦点参数
      tip_visiable: false,
      record: {},
      showGoods: false,
      queryParam: {
        name: '',
        status: -1,
        pageNo: 1,
      },
      spinning: false,
      list_th: [
        { type: 'list', title: '产品名称', span: 6 },
        { type: 'list', title: '分类/已出售量', span: 4 },
        { type: 'list', title: '限制兑换数量', span: 3 },
        { type: 'list', title: '所需积分', span: 3 },
        { type: 'list', title: '状态', span: 2 },
        { type: 'list', title: '排序', span: 2 },
        {
          type: 'list',
          title: '操作',
          span: 3,
          actions: ['编辑', '删除'],
        },
      ],
      pagaData: [],
      totalCount: 0,
      pageSize: 10,
    }
  },
  activated() {
    this.$refs.tableList.$data.localDataSource = []
    this.$refs.tableList.refresh(false)
  },
  created() {
    this.getCatList()
    this.getGoodsList(this.queryParam)
  },
  methods: {
    getGoodsList(params) {
      this.spinning = true
      goodsList(params)
        .then((res) => {
          if (!res.code) {
            this.pagaData = res.data.data
            this.totalCount = res.data.totalCount
          }
          this.spinning = false
        })
        .catch((err) => {
          this.spinning = false
        })
    },
    paginationChange(e) {
      console.log(e, this.queryParam)
      this.getGoodsList(this.queryParam)
    },
    listActions(name, row) {
      console.log('操作', name, row)
      switch (name) {
        case 'order_edit': //编辑
          this.onEdit(row.id)
          break
        case 'delete': //删除
          this.onDelete(row.id)
          break
        default:
          break
      }
    },
    changeTab(val) {
      if (val == 2) {
        this.$router.push({ name: 'IntegralOrder' })
      }
      if (val == 3) {
        this.$router.push({ name: 'IntegralSetting' })
      }
    },
    handleClose() {
      this.cat_id = null
      this.tip_visiable = false
      this.attr = []
      this.choosedGood = null
      this.detail = null
    },
    updateCheck(res) {
      return false
    },
    refresh() {
      console.log(this.queryParam)
      this.getGoodsList({ ...this.queryParam })
    },
    searchGoods() {
      this.queryParam.pageNo = 1
      this.getGoodsList({ ...this.queryParam })
    },
    onAdd() {
      this.selectedAttr = null
      this.commitParams = {}
      this.is_edit = false
      this.visible = true
    },
    async onEdit(id) {
      this.commitParams = {}
      this.is_edit = true
      await getGoods({ id: id }).then((res) => {
        if (res.code == 0) {
          this.tip_visiable = true
          var choose_goods = {
            id: res.data.goods_id,
            name: res.data.name,
          }
          this.cat_id = res.data.cat_id
          this.choosedGood = choose_goods
          this.commitParams = res.data
          this.goods_num = res.data.goods_num
          console.log(this.commitParams)
        } else {
          this.$message.error(res.msg)
        }
      })
      this.visible = true
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    updateAll(type, status) {
      var text = '删除'
      var that = this
      if (type === 'status') {
        text = status === 1 ? '上架' : '下架'
      } else if (type === 'quick_purchase') {
        text = status === 1 ? '加入快速购买' : '关闭快速购买'
      }
      this.$confirm({
        title: '是否批量' + text + '?',
        onOk() {
          goodsUpdateAllApi({
            type: type,
            status: status,
            goods_id: that.selectedRowKeys,
          }).then((res) => {
            if (res.code === 0) {
              that.$nextTick(() => {
                that.$refs.tableList.$data.localDataSource = []
                that.$refs.tableList.refresh(false)
              })
            } else {
              that.$message.error(res.msg)
            }
          })
        },
        onCancel() {},
      })
    },
    onClear() {
      console.log('onClear')
      return false
    },
    onConfirmStatus(value, goodsId) {
      updateStatus({ id: goodsId, status: value }).then((res) => {
        if (res.code === 0) {
          this.getGoodsList(this.queryParam)
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    statusSwitchChange(e) {
      this.onConfirmStatus(e.flag, e.id)
    },
    handleOk() {
      if (this.is_edit == true) {
        this.commitParams.type = 'edit'
      }
      this.commitParams.goods_num = this.goods_num
      this.commitParams.cat_id = this.cat_id
      this.commitParams.detail = this.detail
      saveGoods(this.commitParams).then((res) => {
        if (res.code == 0) {
          this.commitParams = {}
          this.refresh()
          this.$message.success(res.msg)
          this.visible = false
          this.cat_id = null
          this.detail = null
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    onDelete(id) {
      deleteGoods({ id: id }).then((res) => {
        if (res.code === 0) {
          this.refresh()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    updateParam(value, type) {
      this.queryParam[type] = value
    },
    chooseGood(e) {
      if (e.length > 0) {
        this.choosedGood = { ...e[0] }
        console.log(this.choosedGood)
        this.commitParams.goods_id = this.choosedGood.id
        getAttr({ goods_id: this.choosedGood.id }).then((res) => {
          if (res.code === 0) {
            this.attr = res.data.attr
          }
        })
      }
    },
    handleChange: function (value) {
      this.selectedAttr = value
      this.commitParams.attr = this.attr[value].attr_list
      this.goods_num = this.attr[value].num
      this.tip_visiable = true
    },
    handleCatChange(value) {
      this.cat_id = value
      this.commitParams.cat_id = value
    },
    getCatList() {
      getCat().then((res) => {
        if (res.code == 0) {
          this.cat = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    onDescChange: function (content) {
      console.log(content)
      this.detail = content
    },
  },
}
</script>
<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
.search-item {
  margin-left: 10px;
}
</style>
